#!/bin/sh

# AppArmor Ux rules don't sanitize $PATH, which can lead to an
# exploited application (that's allowed to run this script unconfined)
# having this script run arbitrary code, violating that application's
# confinement. Let's prevent that by setting PATH to a list of
# directories where only root can write.
export PATH='/usr/local/bin:/usr/bin:/bin'

set -e
set -u

. gettext.sh
TEXTDOMAIN="tails"
export TEXTDOMAIN

PROFILE="${HOME}/.tor-browser/profile.default"

# Import exec_firefox() and configure_best_tor_browser_locale()
. /usr/local/lib/tails-shell-library/tor-browser.sh

# Allow Torbutton access to the control port filter (for new identity).
# Setting a password is required, otherwise Torbutton attempts to
# read the authentication cookie file instead, which fails.
export TOR_CONTROL_HOST='127.0.0.1'
export TOR_CONTROL_PORT='9052'
export TOR_CONTROL_PASSWD='passwd'
# Hide Torbutton's "Tor Network Settings..." context menu entry since
# it doesn't work in Tails, and we deal with those configurations
# strictly through Tor Launcher.
export TOR_NO_DISPLAY_NETWORK_SETTINGS='yes'


ask_for_confirmation() {
    # Skip dialog if user is already running Tor Browser:
    if pgrep -u amnesia -f "${TBB_INSTALL}/firefox" ; then
        return
    fi

    local dialog_title="`gettext \"Tor is not ready\"`"
    local dialog_text="`gettext \"Tor is not ready. Start Tor Browser anyway?\"`"
    local dialog_start="`gettext \"Start Tor Browser\"`"
    local dialog_cancel="`gettext \"Cancel\"`"
    zenity --question --title "$dialog_title" --text="$dialog_text" \
           --default-cancel --ok-label "$dialog_start" --cancel-label "$dialog_cancel"
}

start_browser() {
    if [ ! -d "${PROFILE}" ]; then
        /usr/local/lib/generate-tor-browser-profile
    fi

    TMPDIR="${PROFILE}/tmp"
    mkdir --mode=0700 -p "$TMPDIR"
    export TMPDIR

    # We need to set general.useragent.locale properly to get
    # localized search plugins (and perhaps other things too). It is
    # not enough to simply set intl.locale.matchOS to true.
    configure_best_tor_browser_locale "${PROFILE}"

    exec_firefox -allow-remote --class "Tor Browser" -profile "${PROFILE}" "${@}"
}


if /usr/local/sbin/tor-has-bootstrapped || ask_for_confirmation; then
    # Torbutton 1.5.1+ uses those environment variables
    export TOR_SOCKS_HOST='127.0.0.1'
    export TOR_SOCKS_PORT='9150'

    start_browser "${@}"
fi
